
extern "C"
{
  #include "lib/printf/printf_port.c"
}

extern "C"
{
  #include "lib\nrf24\nrf24_port.c"
  #include "lib\nrf24\nrf24_device.c"
  #include "lib\nrf24\nrf24_main.c"
}

void ptx_all_clear()
{//清FIFO 清IRQ 拉低CE防止触发TX
  NRF_CE_LOW();
  nrf_tx_flush();
  nrf_rx_flush();
  nrf_clear_irq_src(0x07);
}

void ptx_init()
{
  delay(150);
  PRINT("\r\nstart init PTX.... status: 0x%02X\r\n", nrf_status());
  char adr_msb_first[5] = {0x5A, 0x5A, 0x5A, 0x5A, 0x5A};
  nrf_power_up();
	nrf_set_primary_mode(0); //PTX
	nrf_set_rf_channel(2500);
	nrf_set_rf_data_rate(NRF_VAL_RF_DR_2Mbps);
  nrf_set_auto_retrans(NRF_VAL_ARD_1000uS, NRF_VAL_ARC_5time);
  nrf_set_addr_wid(NRF_VAL_AW_5Bytes);
	nrf_set_pipe_addr(NRF_PIPE0, adr_msb_first, 5);
	nrf_set_tx_addr(adr_msb_first, 5);
	nrf_pipe_enable(NRF_PIPE0);
  ptx_all_clear();
}

size_t get_user_input(char* buf, size_t len)
{
  #define wait_max 100
  int wait = 0;
  size_t sum = 0;
  memset(buf, 0, len);
  PRINT("\r\nInput data......");
  while(sum<len) {
    if (Serial.available()>0) {
      char ch = (char)Serial.read();
      if((ch>='!')&&(ch<='}')) {
        buf[sum] = ch;
      } else {
        char tmp[64] = {0, };
        Serial.setTimeout(wait_max);
        Serial.readBytes(tmp, sizeof(tmp));
        break;
      }
      sum++;
    } else if(sum>0) {
      delay(1);
      wait++;
      if(wait>wait_max) {
        break;
      }
    }
  }
  return sum;
}

char serbuf[33] = {0,};
// the setup routine runs once when you press reset:
void setup() {
  log_init();
  NRF_SPI_INIT();
  ptx_init();
  PRINT("----setup() finished for PTX----");
}
size_t read_rx_data(char* buf, size_t bufsz)
{
  char rxdata[33] = {0, };
	size_t len = nrf_rx_payload_wid();
  if(len>0) {
    nrf_rx_read_payload(rxdata, (char)len);
    if(bufsz<len) {
      len = bufsz;
    }
    memcpy(buf, rxdata, len);
  }
  return len;
}
char send_data(char* buf, size_t len)
{
  nrf_tx_write_payload(buf, (char)len);
  NRF_CE_HIGH();
	NRF_DELAY_uS(13);
	NRF_CE_LOW();
  for(int i=0; i<100; i++) {
		NRF_DELAY_uS(100);
		if(!NRF_IRQ_PIN()) {
			break;
    }
	}
	if(NRF_IRQ_PIN()) {
		PRINT("ERROR, timeout (10 ms)\r\n");
		return -1;
	}
  return nrf_status();
}
// the loop routine runs over and over again forever:
void loop() {
  if(get_user_input(serbuf, sizeof(serbuf)-1)<=0) {
    return;
  }
  PRINT("%s\r\nstart send......", serbuf);
  char status = send_data(serbuf, strlen(serbuf));
  if(status>0) {
    if(NRF_STATUS_MAXRT(status)) {
      PRINT("ERROR, max-retry, status: 0x%02X\r\n", nrf_status());
    } else if(NRF_STATUS_RXDR(status)) {
      memset(serbuf, 0, sizeof(serbuf));
      read_rx_data(serbuf, sizeof(serbuf)-1);
      PRINT("send OK and get ACK data: %s\r\n", serbuf);
    } else {
      PRINT("send OK and no ACK data, status: 0x%02X\r\n", nrf_status());
    }
  }
  ptx_all_clear();
  delay(10);
}
